package com.quyunshuo.module.home.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import com.quyunshuo.module.home.R

class GradientProgressBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 默认颜色值
    @ColorInt
    private var backgroundColor = Color.parseColor("#4D4D4D")

    @ColorInt
    private var startColor = Color.parseColor("#FFA07A")

    @ColorInt
    private var endColor = Color.parseColor("#FF6B6B")

    private var cornerRadius = 8f
    private var progress = 0f // 0-100
    private var showThumb = true
    private var thumbColor = Color.WHITE
    private var thumbSize = 16f
    private var thumbStrokeColor = Color.parseColor("#FF6B6B")
    private var thumbStrokeWidth = 2f



    private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG)
//    private val thumbPaint = Paint(Paint.ANTI_ALIAS_FLAG)
//    private val thumbStrokePaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val gradientMatrix = Matrix()

    init {
        // 从XML属性获取自定义值
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.GradientProgressBar)
        backgroundColor = typedArray.getColor(
            R.styleable.GradientProgressBar_bgColor,
            backgroundColor
        )
        startColor = typedArray.getColor(
            R.styleable.GradientProgressBar_proStartColor,
            startColor
        )
        endColor = typedArray.getColor(
            R.styleable.GradientProgressBar_proEndColor,
            endColor
        )
        cornerRadius = typedArray.getDimension(
            R.styleable.GradientProgressBar_proCornerRadius,
            cornerRadius
        )
        progress = typedArray.getFloat(
            R.styleable.GradientProgressBar_proProgress,
            progress
        )
        showThumb = typedArray.getBoolean(
            R.styleable.GradientProgressBar_showThumb,
            showThumb
        )
        thumbColor = typedArray.getColor(
            R.styleable.GradientProgressBar_thumbColor,
            thumbColor
        )
        thumbSize = typedArray.getDimension(
            R.styleable.GradientProgressBar_thumbSize,
            thumbSize
        )
        thumbStrokeColor = typedArray.getColor(
            R.styleable.GradientProgressBar_thumbStrokeColor,
            thumbStrokeColor
        )
        thumbStrokeWidth = typedArray.getDimension(
            R.styleable.GradientProgressBar_thumbStrokeWidth,
            thumbStrokeWidth
        )
        typedArray.recycle()

        setupPaints()
    }

    private fun setupPaints() {
        // 背景画笔
        backgroundPaint.style = Paint.Style.FILL
        backgroundPaint.color = backgroundColor

        // 进度条画笔（渐变）
        progressPaint.style = Paint.Style.FILL

        // 进度点画笔
        //thumbPaint.style = Paint.Style.FILL
        //thumbPaint.color = thumbColor

        // 进度点描边画笔
        //thumbStrokePaint.style = Paint.Style.STROKE
        //thumbStrokePaint.color = thumbStrokeColor
        //thumbStrokePaint.strokeWidth = thumbStrokeWidth
    }
    // 添加触摸事件处理
    override fun onTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                updateProgressFromTouch(event.x,true)
                return true
            }
            MotionEvent.ACTION_MOVE -> {
                updateProgressFromTouch(event.x,true)
                return true
            }
            MotionEvent.ACTION_UP -> {
                // 抬起时也通知一次，标记为用户操作结束
                updateProgressFromTouch(event.x, true)
                return true
            }
        }
        return super.onTouchEvent(event)
    }


    private fun updateProgressFromTouch(touchX: Float, fromUser: Boolean) {
        // 确保触摸点在有效范围内
        val validX = touchX.coerceIn(0f, width.toFloat())
        // 计算新进度 (0-100)
        val newProgress = (validX / width) * 100f
        setProgress(newProgress, fromUser)
    }


    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 绘制背景
        drawBackground(canvas)

        // 绘制进度条
        drawProgress(canvas)

        // 绘制进度点
        if (showThumb && progress > 0) {
            drawThumb(canvas)
        }
    }

    private fun drawBackground(canvas: Canvas) {
        val rect = RectF(0f, 0f, width.toFloat(), height.toFloat())
        canvas.drawRoundRect(rect, cornerRadius, cornerRadius, backgroundPaint)
    }

    private fun drawProgress(canvas: Canvas) {
        if (progress <= 0) return

        // 计算进度条宽度
        val progressWidth = width * (progress / 100f)

        // 创建渐变
        val gradient = LinearGradient(
            0f, 0f, progressWidth, 0f,
            startColor, endColor, Shader.TileMode.CLAMP
        )

        // 应用渐变
        progressPaint.shader = gradient

        // 绘制进度条
        val progressRect = RectF(0f, 0f, progressWidth, height.toFloat())
        canvas.drawRoundRect(progressRect, cornerRadius, cornerRadius, progressPaint)
    }

    private fun drawThumb(canvas: Canvas) {
        // 计算进度点位置
        val thumbX = width * (progress / 100f)
        val thumbY = height / 2f

        // 绘制描边
        //canvas.drawCircle(thumbX, thumbY, thumbSize, thumbStrokePaint)

        // 绘制填充
        //canvas.drawCircle(thumbX, thumbY, thumbSize - thumbStrokeWidth, thumbPaint)
    }

    // 设置进度 (0-100)
    fun setProgress(progress: Float) {
        this.progress = progress.coerceIn(0f, 100f)
        invalidate()
    }

    // 添加进度变化监听器接口
    interface OnProgressChangeListener {
        fun onProgressChanged(progressBar: GradientProgressBar, progress: Float, fromUser: Boolean)
    }

    private var progressChangeListener: OnProgressChangeListener? = null

    // 设置进度变化监听器
    fun setOnProgressChangeListener(listener: OnProgressChangeListener) {
        progressChangeListener = listener
    }

    private fun setProgress(progress: Float, fromUser: Boolean) {
        val oldProgress = this.progress
        this.progress = progress.coerceIn(0f, 100f)

        // 只有当进度真正改变时才通知监听器
        if (oldProgress != this.progress) {
            invalidate()
            progressChangeListener?.onProgressChanged(this, this.progress, fromUser)
        }
    }

    // 设置背景颜色
    fun setBackgroundColor1(@ColorInt color: Int) {
        backgroundColor = color
        backgroundPaint.color = color
        invalidate()
    }

    // 设置渐变起始颜色
    fun setStartColor(@ColorInt color: Int) {
        startColor = color
        invalidate()
    }

    // 设置渐变结束颜色
    fun setEndColor(@ColorInt color: Int) {
        endColor = color
        invalidate()
    }

    // 设置圆角半径
    fun setCornerRadius(radius: Float) {
        cornerRadius = radius
        invalidate()
    }

    // 设置是否显示进度点
    fun setShowThumb(show: Boolean) {
        showThumb = show
        invalidate()
    }

    // 设置进度点颜色
    fun setThumbColor(@ColorInt color: Int) {
        thumbColor = color
        //thumbPaint.color = color
        invalidate()
    }

    // 设置进度点大小
    fun setThumbSize(size: Float) {
        thumbSize = size
        invalidate()
    }

    // 设置进度点描边颜色
    fun setThumbStrokeColor(@ColorInt color: Int) {
        thumbStrokeColor = color
        //thumbStrokePaint.color = color
        invalidate()
    }

    // 设置进度点描边宽度
    fun setThumbStrokeWidth(width: Float) {
        thumbStrokeWidth = width
        //thumbStrokePaint.strokeWidth = width
        invalidate()
    }
}